package com.vshop.controller.externalInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.external.querydevicebatch.request.RequestQueryBatchDeviceInfo;
import com.vshop.entity.external.querydevicebatch.request.RequestQueryBatchDeviceInfoData;
import com.vshop.entity.external.querydevicebatch.request.RequestQueryBatchDeviceInfoTradeData;
import com.vshop.entity.external.querydevicebatch.response.ResponseQueryBatchDeviceInfo;
import com.vshop.entity.external.querydevicebatch.response.ResponseQueryBatchDeviceInfoData;
import com.vshop.entity.external.querydevicebatch.response.ResponseQueryBatchDeviceInfoTradeData;
import com.vshop.entity.external.querydevicebatch.response.ResponseQueryBatchDeviceInfoTradeDataPackageOrder;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.request.RequestQueryDeviceRealTimeNew;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTime;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeData;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeDataPackageOrder;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.SequenceService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询批量设备的实时信息
 * <p>
 * 接入方可以通过调用该接口，查询某几个设备信息，包括设备的基本信息、设备当前订购的套餐信息等
 * <p>
 * 此接口适用于一个app上绑定多张卡片，用户点击一次“查询”便可获取多张卡片的设备及订单信息
 *
 * @author lm
 * @date 2019/11/04
 */
@RestController
@Api(description = "查询批量设备的实时信息 ")
@Slf4j
public class QueryBatchDeviceController {
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @CrossOrigin
    @PostMapping(value = "queryBatchDevice", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "查询批量设备的实时信息 ", response = ResponseQueryBatchDeviceInfo.class)
    public String queryBatchDevice(@ApiParam @RequestBody RequestQueryBatchDeviceInfo request) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();

        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestQueryBatchDeviceInfo requestPackage = JSONArray.parseObject(requestStr, RequestQueryBatchDeviceInfo.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                RequestQueryBatchDeviceInfoData requestData = requestPackage.getData();
                if (requestData == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerInfoService.getSecretByPartnerCode(partnerCode);
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String version = requestData.getVersion();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(version) || requestData.getTradeData() == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        List<ResponseQueryBatchDeviceInfoTradeData> tradeDataList = new ArrayList<ResponseQueryBatchDeviceInfoTradeData>();

                        ResponseQueryBatchDeviceInfoTradeData tradeData = null;

                        for (RequestQueryBatchDeviceInfoTradeData requestTradeData : requestData.getTradeData()) {

                            String deviceCode = requestTradeData.getDeviceCode();
                            if (StringUtils.isBlank(deviceCode)) {
                                log.info("请求报文不合法:tradeData参数不合法");
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                return jsonString;
                            } else {

                                String str = JSON.toJSONString(requestData);
                                String sign = utils.calculateSignature(str);
                                if (!requestSign.equalsIgnoreCase(sign)) {
                                    jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                    return jsonString;

                                } else {

                                    RequestQueryDeviceRealTimeNew deviceInfo = new RequestQueryDeviceRealTimeNew();
                                    deviceInfo.setDeviceId(deviceCode);
                                    deviceInfo.setPartnerCode(partnerCode);
                                    deviceInfo.setSecret(secret);
                                    //组装需要的json去请求报文
                                    String requestInterface = JSON.toJSONString(deviceInfo);
                                    String url = requestURI + Constant.iot_queryDeviceRealTimeNew_2;
                                    // 发送post请求，并接收返回结果
                                    String returnStr = HttpUtil.httpPost(url, requestInterface);
                                    ResponseQueryDeviceRealTime response = JSONArray.parseObject(returnStr, ResponseQueryDeviceRealTime.class);

                                    if (response != null) {

                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(response.getRetCode())) {


                                            if (response.getTradeData() != null && response.getTradeData().size() >= 1) {

                                                for (ResponseQueryDeviceRealTimeTradeData tr : response.getTradeData()) {

                                                    if (StringUtils.isNotBlank(tr.getLifecycle()) && tr.getPackageOrder() != null && tr.getPackageOrder().size() >= 1) {

                                                        ResponseQueryBatchDeviceInfoTradeDataPackageOrder pOrder = new ResponseQueryBatchDeviceInfoTradeDataPackageOrder();

                                                        for (ResponseQueryDeviceRealTimeTradeDataPackageOrder porder : tr.getPackageOrder()) {

                                                            if (StringUtils.isNotBlank(porder.getOrderCode())) {

                                                                pOrder.setPackageCode(porder.getPackageCode());
                                                                pOrder.setPackageName(porder.getPackageName());
                                                                pOrder.setPackageType(porder.getPackageType());
                                                                pOrder.setOrderPeriod(porder.getOrderPeriod());
                                                                pOrder.setOrderId(porder.getOrderCode());


                                                                if (StringUtils.isNotBlank(porder.getBuyType())) {
                                                                    pOrder.setBuyType(porder.getBuyType());
                                                                } else {
                                                                    pOrder.setBuyType("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getFlow())) {
                                                                    pOrder.setFlow(porder.getFlow());
                                                                } else {
                                                                    pOrder.setFlow("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getUsedFlow())) {
                                                                    pOrder.setUsedFlow(porder.getUsedFlow());
                                                                } else {
                                                                    pOrder.setUsedFlow("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getFlowUseRate())) {
                                                                    pOrder.setFlowUseRate(porder.getFlowUseRate());
                                                                } else {
                                                                    pOrder.setFlowUseRate("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getOrderUsedFlow())) {
                                                                    pOrder.setOrderUsedFlow(porder.getOrderUsedFlow());
                                                                } else {
                                                                    pOrder.setOrderUsedFlow("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getOrderDate())) {
                                                                    pOrder.setOrderDate(porder.getOrderDate());
                                                                } else {
                                                                    pOrder.setOrderDate("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getActiveDate())) {
                                                                    pOrder.setActiveDate(porder.getActiveDate());
                                                                } else {
                                                                    pOrder.setActiveDate("");
                                                                }
                                                                if (StringUtils.isNotBlank(porder.getExpireDate())) {
                                                                    pOrder.setExpireDate(porder.getExpireDate());
                                                                } else {
                                                                    pOrder.setExpireDate("");
                                                                }


                                                            }

                                                        }

                                                        tradeData = new ResponseQueryBatchDeviceInfoTradeData();
                                                        tradeData.setDeviceCode(tr.getDeviceId());
                                                        tradeData.setOtaFlag(tr.getOtaFlag());
                                                        tradeData.setBipFlag(tr.getBipFlag());
                                                        tradeData.setMultiImsiFlag(tr.getMultiImsiFlag());
                                                        tradeData.setLifecycle(tr.getLifecycle());
                                                        tradeData.setLifecycleStartTime(tr.getLifecycleStartTime());
                                                        tradeData.setLifecycleEndTime(tr.getLifecycleEndTime());
                                                        tradeData.setLifecycleSlientPeriod(tr.getLifecycleSlientPeriod());
                                                        tradeData.setLifecycleShutdownPeriod(tr.getLifecycleShutdownPeriod());
                                                        tradeData.setPackageOrder(pOrder);
                                                        tradeDataList.add(tradeData);


                                                    } else {
                                                        // 设备正在使用期内，但是没有订单信息,此时异常
                                                        continue;
                                                    }


                                                }
                                            } else {

                                                //tradeData = new ResponseQueryBatchDeviceInfoTradeData();
                                                //tradeDataList.add(tradeData);
                                                continue;

                                            }


                                        } else {
                                            //tradeData = new ResponseQueryBatchDeviceInfoTradeData();
                                            //tradeDataList.add(tradeData);
                                            continue;
                                        }


                                    } else {
                                        //tradeData = new ResponseQueryBatchDeviceInfoTradeData();
                                        //tradeDataList.add(tradeData);
                                        continue;

                                    }

                                }
                            }

                        }

                        ResponseQueryBatchDeviceInfoData data = new ResponseQueryBatchDeviceInfoData();
                        data.setConnSeqNo(ConnSeqNo);
                        data.setPartnerCode(partnerCode);
                        data.setTradeType(tradeType);
                        data.setTradeTime(tradeTime);
                        data.setRetCode("0000");
                        data.setRetMsg("success");
                        data.setTradeData(tradeDataList);

                        ResponseQueryBatchDeviceInfo res = new ResponseQueryBatchDeviceInfo();
                        res.setData(data);
                        res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                        jsonString = JSON.toJSONString(res);
                        log.info("响应报文：" + jsonString);
                        return jsonString;


                    }
                }
            }
        }
    }


}
